package com.css.upms.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.css.common.core.constent.CommonConstant;
import com.css.common.core.utils.R;
import com.css.upms.api.entity.SysMenu;
import com.css.upms.api.entity.SysRole;
import com.css.upms.api.entity.SysRoleMenu;
import com.css.upms.biz.constent.UpmsConstent;
import com.css.upms.biz.mapper.SysMenuMapper;
import com.css.upms.biz.mapper.SysRoleMapper;
import com.css.upms.biz.mapper.SysRoleMenuMapper;
import com.css.upms.biz.service.SysRoleMenuService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色权限关系
 *
 * @author hanyx
 * @date 2019-05-03 02:46:44
 */
@Service("sysRoleMenuService")
@AllArgsConstructor
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    private final CacheManager cacheManager;
    private final SysRoleMapper sysRoleMapper;
    private final SysMenuMapper sysMenuMapper;


    /**
     * 角色权限关系简单分页查询
     *
     * @param sysRoleMenu 角色权限关系
     * @return
     */
    @Override
    public IPage<SysRoleMenu> getSysRoleMenuPage(Page<SysRoleMenu> page, SysRoleMenu sysRoleMenu) {
        return baseMapper.getSysRoleMenuPage(page, sysRoleMenu);
    }

    /**
     * @param roleId  角色
     * @param menuIds 菜单ID拼成的字符串，每个id之间根据逗号分隔
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "menu_details", key = "#roleId + '_menu'")
    public R saveRoleMenus(String roleId, String menuIds) {
        if (StringUtils.isBlank(roleId)) {
            return R.buildError("角色ID不能为空");
        }
        // roleId 是 admin 不能删除菜单权限
        SysRole sysRole = sysRoleMapper.selectById(roleId);
        if (StringUtils.equals(UpmsConstent.ADMIN_ROLE_CODE, sysRole.getRoleCode())) {
            if (StringUtils.isBlank(menuIds)) {
                return R.buildError("管理员不能没有菜单权限");
            } else {
                List<SysMenu> menuList = sysMenuMapper.selectBatchIds(Arrays.stream(menuIds.split(",")).collect(Collectors.toList()));
                if (CollectionUtils.isEmpty(menuList) ||
                        !(menuList.stream().anyMatch(menu -> StringUtils.equals(UpmsConstent.PERMISSIONS_MENU_NAME, menu.getMenuName())))) {
                    return R.buildError("管理员不能没有菜单权限");
                }
            }
        }

        this.remove(Wrappers.<SysRoleMenu>query().lambda()
                .eq(SysRoleMenu::getRoleId, roleId));

        if (StringUtils.isBlank(menuIds)) {
            return new R(Boolean.TRUE);
        }
        List<SysRoleMenu> roleMenuList = Arrays
                .stream(menuIds.split(","))
                .map(menuId -> {
                    SysRoleMenu roleMenu = new SysRoleMenu();
                    roleMenu.setRoleId(roleId);
                    roleMenu.setMenuId(String.valueOf(menuId));
                    return roleMenu;
                }).collect(Collectors.toList());

        //清空userinfo
        cacheManager.getCache("user_details").clear();
        return new R(this.saveBatch(roleMenuList));
    }

}
